<!--
 * @Author: jiutian
 * @Date: 2023-01-31 11:17:03
 * @LastEditTime: 2023-02-17 09:20:45
 * @LastEditors:  
-->
<script setup lang="ts">
import { ref, reactive, Ref, onBeforeMount } from "vue";
import request from "@api";
import type { FormInstance, FormRules } from "element-plus";
import _toLower from "loadsh/toLower";
import md5 from "md5";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "@/store";
// 定义 FormData 接口类型 限制 对象属性值类型
interface FormData {
  password: string;
  captchaCode: string;
  phoneNumber: string;
  smsCode: string;
}
let formData: FormData = reactive({
  password: "",
  captchaCode: "",
  phoneNumber: "",
  smsCode: "",
});
const store = useStore();

const validatePhone = (rule: any, value: any, callback: any) => {
  if (
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
      value
    )
  ) {
    callback();
  } else {
    callback(new Error("请输入正确的手机格式"));
  }
};

const checkCaptchaCode = (rule: any, value: any, callback: any) => {
  if (_toLower(value) != _toLower(svgCaptcha.code)) {
    callback("验证码不正确");
    getSvgCaptcha();
  } else {
    callback();
  }
};

let isLoginType: Ref<string> = ref("");
let title: Ref<string> = ref("密码登录");
let showLogin: Ref<boolean> = ref(true);
let svgCaptcha = reactive({
  svg: "",
  code: "",
});
let showPwd: boolean = ref(false);
let formRef = ref<FormInstance>();
let errorTxt = ref("");
let time = ref(60);
let timer = ref();
let isSend = ref(false);
let phoneNumberRef = ref();
const $router = useRouter();

let rules = reactive<FormRules>({
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captchaCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { validator: checkCaptchaCode, trigger: "sumbit" },
  ],
  phoneNumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  smsCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

function changeDOMstate(type: string) {
  if (type == "1") {
    isLoginType.value = "1";
    setTimeout(() => {
      showLogin.value = false;
      title.value = "短信登录";
    }, 300);
  } else {
    isLoginType.value = "2";
    setTimeout(() => {
      showLogin.value = true;
      title.value = "密码登录";
    }, 300);
  }
  errorTxt.value = "";
  getSvgCaptcha();
}

function getSvgCaptcha() {
  request["entry/getSvgCaptcha"]().then((res: any) => {
    if (res.code == 200) {
      svgCaptcha.code = res.data.code;
      svgCaptcha.svg = res.data.svg;
    }
  });
}

function sengMsg() {
  phoneNumberRef.value
    .validate()
    .then(() => {
      isSend.value = true;
      timer.value = setInterval(() => {
        time.value--;
        if (time.value < 0) {
          isSend.value = false;
          time.value = 60;
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);
      request["entry/sendMsg"]({
        data: {
          phoneNumber: formData.phoneNumber,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          ElNotification({
            type: "success",
            title: "提示",
            message: res.msg,
            showClose: false,
          });
        } else {
          ElNotification({
            type: "error",
            title: "提示",
            message: res.msg,
            showClose: false,
          });
        }
      });
    })
    .catch(() => {});
}

function saveLogin(type: string) {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 密码登录
      if (showLogin.value) {
        request["entry/entryPwd"]({
          data: {
            phoneNumber: formData.phoneNumber,
            password: md5(formData.password),
          },
        }).then((res: any) => {
          if (res.code == 200) {
            ElNotification({
              type: "success",
              title: "提示",
              message: res.msg,
              showClose: false,
            });
            localStorage.setItem("token", res.data);
            store.loginFunc();
            $router.replace({
              name: "home",
            });
          } else {
            if (res.errorPwd) {
              errorTxt.value = res.msg;
              ElNotification({
                type: "error",
                title: "提示",
                message: res.msg,
                showClose: false,
              });
            } else {
              ElNotification({
                type: "error",
                title: "提示",
                message: res.msg,
                showClose: false,
              });
            }
          }
        });
      }
      // 验证码登录
      else {
        if (!isSend.value && formData.smsCode)
          return (errorTxt.value = "请先发送验证码");
        request["entry/entryPhone"]({
          data: {
            phoneNumber: formData.phoneNumber,
            smsCode: formData.smsCode,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            ElNotification({
              type: "success",
              title: "提示",
              message: res.msg,
              showClose: false,
            });

            localStorage.setItem("token", res.data);
            store.loginFunc();
            $router.replace({
              name: "home",
            });
          } else {
            if (res.error) {
              errorTxt.value = res.msg;
              ElNotification({
                type: "error",
                title: "提示",
                message: res.msg,
                showClose: false,
              });
            } else {
              ElNotification({
                type: "error",
                title: "提示",
                message: res.msg,
                showClose: false,
              });
            }
          }
        });
      }
    }
  });
}

// function downFile() {
//   // request["entry/getXlsx"]().then((res) => {
//   //   console.log(res);
//   // });
//   location.href = "/api/entry/getXlsx";
// }

// 生命周期
onBeforeMount(() => {
  getSvgCaptcha();
  localStorage.clear();
});
</script>

<template>
  <div class="login">
    <div class="mian_box">
      <!-- <button @click="downFile">测试下载</button> -->
      <div class="top-title">
        <div class="title">博客</div>
        <div class="desc">我的个人博客</div>
      </div>
      <div
        class="content"
        :class="{
          toRegister: isLoginType == '1',
          toLogin: isLoginType == '2',
        }"
      >
        <div class="left"></div>
        <div class="right">
          <div class="title">
            <span>{{ title }}</span>
          </div>
          <div class="form">
            <template v-if="showLogin">
              <el-form
                :model="formData"
                ref="formRef"
                label-width="65px"
                :rules="rules"
              >
                <el-form-item size="large" label="账户" prop="phoneNumber">
                  <el-input
                    placeholder="请输入手机号"
                    v-model.trim="formData.phoneNumber"
                  />
                </el-form-item>
                <el-form-item
                  size="large"
                  label="密码"
                  prop="password"
                  class="pwd"
                  :error="errorTxt"
                >
                  <el-input
                    placeholder="请输入密码"
                    :type="showPwd ? 'text' : 'password'"
                    v-model.trim="formData.password"
                  />
                  <el-icon
                    v-if="formData.password"
                    class="ElIcon"
                    @click="showPwd = !showPwd"
                    color="#999"
                  >
                    <View v-if="!showPwd" />
                    <Hide v-else />
                  </el-icon>
                </el-form-item>
                <el-form-item
                  label="验证码"
                  prop="captchaCode"
                  class="captchaCodePwd"
                  size="large"
                >
                  <el-input
                    placeholder="请输入验证码"
                    v-model.trim="formData.captchaCode"
                    maxlength="4"
                  />
                  <div
                    @click="getSvgCaptcha"
                    class="captchaCode"
                    v-html="svgCaptcha.svg"
                  ></div>
                </el-form-item>
                <el-form-item>
                  <div class="tools">
                    <span @click="changeDOMstate('1')">短信登录</span>
                    <span @click="$router.push({ name: 'forget' })"
                      >忘记密码</span
                    >
                  </div>
                </el-form-item>
                <el-form-item class="btn_formitem">
                  <div class="buttons">
                    <el-button type="primary" @click="saveLogin('1')"
                      >登录/注册</el-button
                    >
                  </div>
                </el-form-item>
              </el-form>
            </template>
            <template v-else>
              <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-width="65px"
              >
                <el-form-item
                  label="手机号"
                  ref="phoneNumberRef"
                  size="large"
                  prop="phoneNumber"
                >
                  <el-input
                    placeholder="请输入手机号"
                    v-model.trim="formData.phoneNumber"
                  />
                </el-form-item>
                <el-form-item
                  label="验证码"
                  size="large"
                  class="smsCode"
                  prop="smsCode"
                  :error="errorTxt"
                >
                  <el-input
                    placeholder="请输入验证码"
                    maxlength="6"
                    v-model.trim="formData.smsCode"
                  />
                  <el-button
                    type="primary"
                    :disabled="isSend"
                    @click="sengMsg"
                    >{{
                      isSend ? time + "秒后可重发" : "发送验证码"
                    }}</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <div class="tools" style="justify-content: flex-end">
                    <span @click="changeDOMstate('2')">密码登录</span>
                  </div>
                </el-form-item>
                <el-form-item class="btn_formitem">
                  <div class="buttons">
                    <el-button type="primary" @click="saveLogin('2')"
                      >登录</el-button
                    >
                  </div>
                </el-form-item>
              </el-form>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  background-color: #ededed;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  .mian_box {
    margin-top: 15vh;
    width: 550px;
    .top-title {
      text-align: center;
      .title {
        font-size: 28px;
        font-weight: bold;
        letter-spacing: 15px;
      }
      .desc {
        color: #999;
        font-size: 14px;
        letter-spacing: 4px;
      }
    }
    .content {
      margin-top: 15px;
      height: 350px;
      position: relative;
      overflow: hidden;
      border-radius: 5px;

      .left {
        z-index: 99;
        position: absolute;
        top: 0px;
        left: -350px;
        width: 550px;
        height: 350px;
        background-color: aqua;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
        transition: 0.8s all;
        background-image: url("@imgs/login_left_bg.jfif");
        background-size: 100% 100%;
      }
      .right {
        background-color: #fff;
        position: absolute;
        top: 0px;
        right: 0px;
        width: 350px;
        height: 350px;
        padding: 15px;
        transition: 0.8s all;
        .title {
          margin-bottom: 20px;
          position: relative;
          height: 25px;

          span {
            font-size: 18px;
            font-weight: 600;
            position: absolute;
            left: 0px;
            transition: 0.8s all;
          }
        }
        :deep() {
          .form {
            .captchaCodePwd {
              .el-form-item__content {
                flex-wrap: nowrap;
                align-items: center;
                .el-input {
                  .el-input__wrapper {
                    border-top-right-radius: 0px;
                    border-bottom-right-radius: 0px;
                  }
                }
                .captchaCode {
                  height: 40px;
                  width: 120px;
                  border: 1px solid #dcdfe6;
                  border-left: none;
                }
              }
            }
            .tools {
              font-size: 14px;
              color: #999;
              width: 100%;
              display: flex;
              justify-content: space-between;
              span {
                cursor: pointer;
                user-select: none;
              }
            }
            .buttons {
              width: 100%;
              .el-button {
                width: 100%;
              }
            }
            .btn_formitem {
              .el-form-item__content {
                margin-left: 0 !important;
              }
            }

            .pwd {
              position: relative;
              .ElIcon {
                position: absolute;
                top: 50%;
                right: 5px;
                transform: translate(-50%, -50%);
              }
              .el-input__wrapper {
                padding-right: 35px;
              }
            }
            .smsCode {
              .el-form-item__content {
                flex-wrap: nowrap;
                .el-input__wrapper {
                  border-top-right-radius: 0px;
                  border-bottom-right-radius: 0px;
                }
                .el-button {
                  border-top-left-radius: 0px;
                  border-bottom-left-radius: 0px;
                  padding: 12px;
                  width: 120px;
                }
              }
            }
          }
        }
      }
    }

    .toRegister {
      .left {
        left: 350px;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
      }
      .right {
        right: 200px;
        .title span {
          left: 248px;
        }
      }
    }

    .toLogin {
      .left {
        left: -350px;
      }
      .right {
        right: 0px;
        .title span {
          right: 0px;
        }
      }
    }
  }
}
</style>